package com.sinux.mms.controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.sinux.mms.common.init.SpringInit;
import com.sinux.mms.entity.Record;
import com.sinux.mms.entity.Suser;
import com.sinux.mms.service.SuserServiceI;
import com.sinux.mms.util.MUtil;

/**
 * 
 * @Description 用户控制层
 * @date 2017-06-14 09:26:47
 */
@Controller
@SuppressWarnings("all")
public class SuserController {
	
	@Autowired
	private SuserServiceI userService;
	
	@RequestMapping("/pageToAddUser")
	public String pageToAdduser() {
		return "modules/sysuser/sysuser_manager";
	}
	
	@RequestMapping("/pageToEditUser")
	public String pageToEditUser() {
		return "modules/sysuser/sysuser_edit";
	}
	/**
	 * TODO 查询全部用户
	 * @param request
	 * @param response
	 * @param model
	 */
	@ResponseBody
	@RequestMapping("/getUserList")
	public Map<String, Object> getUserList(HttpServletRequest request, HttpServletResponse response,Model model) {
		Map<String, Object> map=new HashMap<String, Object>();
		int offset =Integer.valueOf(request.getParameter("offset")); //当前页第一条数据(包含)  
	    int limit = Integer.valueOf(request.getParameter("limit")); //每页多少条数据  
		//页数=当前页第一条数据/每页多少条数据 +1
	    List<Suser> records=userService.findAllUserList();
		int total=userService.findAllUserList().size();
		map.put("rows", records);
		map.put("total", total);
		return map;
	}
	/**
	 * 登录页面
	 * @return
	 */
	@RequestMapping("/")
	public String login1() {
		// 如果已登录，再次访问主页，则退出原账号。
		// 如果已经登录，则跳转到管理首页
		return "modules/logReg";
	}
	
	/**
	 * 登录验证后,跳转页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping("/sys")
	public String index(HttpServletRequest request, HttpServletResponse response, Model model){
		Suser user = (Suser) request.getSession().getAttribute("mms");// user为空
		// 判断是否为空
		if (user == null) {
			return "modules/logReg";
		} else {
			model.addAttribute("user",user);
			return "modules/index";
		}
		
	}
	
	
	/**
	 * 退出登录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/outLogin")
	public String outLogin(HttpServletRequest request,HttpServletResponse response){
		request.getSession().removeAttribute(SpringInit.SESSION_SUSER_NAME);
		return "modules/logReg";
	}
	
	/**
	 * 验证登录
	 * @param request
	 * @param response
	 * @param user
	 * @return map
	 * @throws IOException 
	 */
	@ResponseBody
	@RequestMapping("/checklog")												
	public void checkLogin(HttpServletRequest request, HttpServletResponse response, Suser user) throws IOException {
		Map<String, Object> map = new HashMap<String, Object>();
		if(user!=null){
			user.setPwd(MUtil.encryptByMd5(user.getPwd()));//MD5加密
			System.out.println(user.getLogname()+"*****"+user.getPwd());
			Suser _user = userService.login(user);
			//User _user=null;
			if (_user == null) {				
				map.put("success", false);
				map.put("msg", "登录失败！");
			} else {
				System.out.println("查找成功");
				request.getSession().setAttribute(SpringInit.SESSION_SUSER_NAME, _user);
				map.put("success", true);
				map.put("msg", "登录成功！");
			}
			
		}else{
			map.put("success", false);
			map.put("msg", "登录异常,未获取信息!");
			
		}
		
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(JSONObject.toJSONString(map));
		response.getWriter().close();
		response.getWriter().flush();
		
	}
	
	/**
	 * 注册
	 * @param request
	 * @param response
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/reguser")
	public Map<String, Object> regUser(HttpServletRequest request,HttpServletResponse response,Suser user){
		Map<String, Object> map =new HashMap<String, Object>();
		System.out.println("user ID:"+user.getId());
		if (user == null) {
			map.put("success", false);
			map.put("msg", "注册失败！");
		} else {
			try {
				user.setPwd(MUtil.encryptByMd5(user.getPwd()));//MD5加密
				userService.reg(user);
				request.getSession().setAttribute(SpringInit.SESSION_SUSER_NAME, user);
			} catch (Exception e) {
				System.out.println("注册出错");
				e.printStackTrace();
				map.put("success", false);
				map.put("msg", "注册失败！");
				return map;
			}
			map.put("success", true);
			map.put("msg", "注册成功！");
		}
		return map;
	}
	
	@RequestMapping("/uploadSysuserFile")
	public void uploadSysuserFile(@RequestParam("file") MultipartFile file,HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		String table_id=request.getParameter("table_id");
		String fileName=file.getOriginalFilename();
		String prefix=fileName.substring(fileName.lastIndexOf(".")+1);//后缀
//		String uuid = UUID.randomUUID().toString().replaceAll("\\-", "");
//        String path=BigFileUploadUtil.getUploadFileSavePath();
//        File tempFile = new File(path,String.valueOf(uuid+"."+prefix));  
//        if (!tempFile.getParentFile().exists()) {  
//            tempFile.getParentFile().mkdir();  
//        }  
//        if (!tempFile.exists()) {  
//            tempFile.createNewFile();  
//        }
//        file.transferTo(tempFile);
		JSONObject jsonobj=new JSONObject();
        
        jsonobj.put("fileName", fileName);
        jsonobj.put("prefix", prefix);
        response.getWriter().write(jsonobj.toString());
        response.getWriter().close();
        response.getWriter().flush();	
	}
}
